package net.oschina.simpleplus.sso.web;

import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class SsoController {
	
	private static boolean checkRequestCookie(HttpServletRequest req){
		Cookie[] cookies = req.getCookies();
		if(cookies != null)
			for(Cookie ck : cookies){
				if("token".equals(ck.getName())){
					System.out.println(ck.getValue());
					return true;
				}
			}
		return false;
	}

	@RequestMapping(value={"/index","/"}, method= RequestMethod.GET)
	public String index(){
		return "/index";
	}
	
	@RequestMapping(value="/login", method= RequestMethod.POST)
	public String login(@RequestParam("username") String username, 
			@RequestParam("password") String password, 
			@RequestParam(value = "gotourl", required = false) String gotourl, 
			
			HttpServletResponse resp){
		if("wang".equals(username) && "wang".equals(password)){
			Cookie cookie = new Cookie("token", UUID.randomUUID().toString());
			cookie.setPath("/");
			cookie.setMaxAge(24*60*60);
			resp.addCookie(cookie);
			if(StringUtils.isEmpty(gotourl)){
				return "success";
			}
			return gotourl;
		}
		return "index";
	}
	
	@RequestMapping(value="/demo1", method= RequestMethod.GET)
	public String demo1(HttpServletRequest req, Model m){
		if(checkRequestCookie(req)){
			return "demo1";
		}
		m.addAttribute("gotourl", "demo1");
		return "index";
	}
	
	@RequestMapping(value="/demo2", method= RequestMethod.GET)
	public String demo2(HttpServletRequest req, Model m){
		if(checkRequestCookie(req)){
			return "demo2";
		}
		m.addAttribute("gotourl", "demo2");
		return "index";
	}
}
